package com.liang.demo02;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @Author:liangli
 * @Date:2020/11/17 14:22
 */
//第三种方式创建线程  实现callable接口
    //callable好处
    //1.可以定义返回值
    //2.可以抛出异常
public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;

    public TestCallable(String url,String name){
        this.name=name;
        this.url=url;
    }
    public Boolean call() throws Exception {
        WebDownloader downloader=new WebDownloader();
        downloader.downloader(url,name);
        System.out.println("下载的图片名为"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1=new TestCallable("https://pics0.baidu.com/feed/37d3d539b6003af35ed8cbb408c25f5b1238b6f7.jpeg?token=20137b735026d772d22affcc7ed472dd","1.png");
        TestCallable t2=new TestCallable("https://pics6.baidu.com/feed/3bf33a87e950352ae94044a110ab62f5b3118b61.jpeg?token=d0f2078e353de1a67cc8c8091e02c81b","2.png");
        TestCallable t3=new TestCallable("https://pics1.baidu.com/feed/5882b2b7d0a20cf4f1c71f9732e1d231adaf9917.jpeg?token=f6bcae9605040ee493ebe2146c371611","3.png");
        //创建执行任务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        //关闭服务
        ser.shutdown();



    }

}

//下载器
class WebDownloader{
    //下载方法
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("io异常，downloader出现问题");
        }
    }
}